package com.bourse.at.indicator;

import org.joda.time.DateMidnight;

import com.bourse.core.exceptions.TimeSerieException;
import com.bourse.core.utils.Cotation;
import com.bourse.core.utils.TimeSerie;
import com.bourse.core.utils.TimeSerieObject;


public class SMA extends Indicator {

	int period;

	public SMA(TimeSerieObject<Cotation> cotations, int period) {
		super(cotations);
		this.period = period;
	}
	
	public TimeSerie calculate() {
		try{
			TimeSerie ts = new TimeSerie();
			for (int i = 0; i < cotations.size(); i++) {
				DateMidnight date = cotations.getDate(i);
				Cotation cotation = cotations.getValue(date);
				if(i>=period){
					int startIndex = i - period;
					int endIndex = i;
					double sma = 0.0D;
					for(int j=startIndex ; j<=endIndex ; j++){
						sma+= cotation.getCours();
					}
					sma = sma/period;
					ts.add(date, sma);
				}else{
					ts.add(date, 0.0D);
				}
			}
		} catch(TimeSerieException e ) {
			LOGGER.error("[Indicator] - Error while building SMA: "+e.getMessage());
		}
		
		return null;
	}

}
